<template>
  <basic-container>
    <avue-crud :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      ref="crud"
      :search.sync="query"
      v-model="form"
      @row-click="handleRowClick"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <table-right :crud='$refs.crud' :data='data' :add-permission="true" :handle-add="addFn" :refreshChange='refreshChange'></table-right>
      </template>
      <template slot="materialNo" slot-scope="{row}">
        <span>{{row.materialNo}}</span>
      </template>

      <template slot="status" slot-scope="{row}">
        <el-switch
          size="mini"
          v-model="row.status"
          active-value="1"
          inactive-value="2"
          @change="changeEnableIdentity(row)"
          active-color="#13ce66"
          inactive-color="#ff4949">
        </el-switch>
      </template>

      <template slot-scope="{row}" slot="menu">
        <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
          <el-button icon="el-icon-edit" size="small" type="text"  @click.stop="editFn(row)" v-if="permission.bom_formula_edit"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
          <el-button icon="el-icon-delete" size="small" type="text" @click.stop="rowDel(row)"  v-if="permission.bom_formula_del"></el-button>
        </el-tooltip>

      </template>
    </avue-crud>
    <el-tabs type="border-card" class='tabs'>
      <el-tab-pane label="配方">
        <formulaCom :BOMdata="BOMdata" :mainStatus="mainStatus" :BOMloading="BOMloading" @getBom="getBom" />
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="title"
               v-dialogdrag
               :destroy-on-close="true"
               show-close
               :visible.sync="showDialog"
               width="70%"
               append-to-body='true'
               top="3%"
               :close-on-click-modal='false'>
      <mainCom @reload="reload" :openType="openType" :detailId="detailId" @close="showDialog=false" v-if="showDialog" />
    </el-dialog>
  </basic-container>
</template>

<script>
import * as product from '@/api/project/productData/product';
import { mapGetters, mapState } from 'vuex';
import { init } from '@/mixins/init';
import { searchSpan, culomnSpan } from "@/api/span";
import formulaCom from './tabs.vue'
import mainCom from './addCom.vue'
import {updateStatus} from "@/api/project/productData/product";

export default {
  mixins: [init],
  components: { formulaCom, mainCom },
  data() {
    return {
      BOMloading: false,
      BOMdata: [],
      mainStatus: '',
      currentMaterialNo: '', //当前选中的产品编码
      openType: '',
      detailId: '',
      title: '',
      query: {
        // productType: 'PC'
      },
      showDialog: false,
      option: {
        highlightCurrentRow: true,
        menuWidth: 160,
        tip: false,
        index: true,
        border:true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        menu: true,
        searchMenuSpan:searchSpan(2),
        column: [
          {
            label: '配方号',
            prop: 'formulaNo',
            maxlength: 30,
            minWidth: 120,
            // search: true,
            // searchSpan: culomnSpan(),
            overHidden: true,
            display: false,
          },
          // {
          //   label: '配方名称',
          //   prop: 'formulaName',
          //   maxlength: 30,
          //   minWidth: 120,
          //   overHidden: true,
          //   display: false,
          // },
          {
            label: '产品编码',
            prop: 'materialNo',
            search: true,
            searchSpan: culomnSpan(),
            minWidth: 150,
            sortable: true,
            overHidden: true,
          }, {
            label: '产品名称',
            prop: 'materialName',
            search: true,
            searchSpan: culomnSpan(),
            minWidth: 150,
            sortable: true,
            overHidden: true,
          },
          {
            label: '启用',
            prop: 'status',
            slot:true,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['permission']), //权限映射
    ...mapState({
      headers: (state) => ({ 'Blade-Auth': `bearer ${state.user.token}` }),
    }),
  },
  methods: {
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {
        // productType: 'PC'
      };
      this.onLoad(this.page);
    },
    handleRowClick (row) {
      this.clickRow = row;
      this.mainStatus = row.status
      this.currentMaterialNo = row.materialNo;
      this.getBom();
    },
    changeEnableIdentity(row){
      updateStatus({id:row.id,status:row.status}).then(res=>{
        this.$message.success("操作成功");
        this.onLoad(this.page)
      }).catch(()=>{
        this.onLoad(this.page)
      })
    },
    addFn () {
      this.openType = 'add'
      this.title = '新增'
      this.showDialog = true
    },
    viewFn (row) {
      this.openType = 'view'
      this.title = '查看'
      this.detailId = row.id
      this.showDialog = true
    },
    copyFn (row) {
      this.openType = 'copy'
      this.title = '复制'
      this.detailId = row.id
      this.showDialog = true
    },
    editFn (row) {
      this.openType = 'edit'
      this.title = '编辑'
      this.detailId = row.id
      this.showDialog = true
    },
    changeStatus (row) {
      let data = {
        id: row.id,
        status: row.status == 1 ? 2 : 1,
        materialNo: row.materialNo
      }
      product.updateStatus(data).then(res => {
        this.$message.success(res.data.msg)
        this.onLoad(this.page)
      })
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        product.bomRemove(row.id).then(res => {
          this.onLoad(this.page);
          this.$message.success(res.data.msg)
        }).catch(() => {})
      }).catch(() => {})
    },

    getBom() {
      this.BOMloading = true
      this.BOMdata = []
      product.productBomList(this.currentMaterialNo).then((res) => {
        const data = res.data.data;
        this.BOMdata = data.map(item => {
          item.materialTypes = [item.productFlag, item.productType]
          return item
        })
        this.BOMloading = false
      }).catch(() => {
        this.BOMloading = false
      })
    },
    onLoad(page, params = this.query) {
      //加载table
      this.query.dataSource = '1';
      this.query.productType = this.query.productType || undefined
      this.loading = true;
      product.bomList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data
        this.page.total = data.total;
        data.records.forEach((ele)=>{
          ele.status = ele.status+""
        })
        this.data = data.records;
        this.loading = false;
        if (this.data.length > 0) {
          this.$nextTick(() => {
            this.$nextTick(() => {
              this.$refs.crud.setCurrentRow(this.data[0]);
              this.handleRowClick(this.data[0])
            });
          });
        } else {
          setTimeout(() => {
            this.$EventBus.$emit('publicBtn', {
              add:this.permission.bom_formula_add,
            })
          }, 200)
          this.BOMdata.length = 0;
          this.BOMdata = [];
        }
      });
    },
    reload (type) {
      this.onLoad(this.page)
      if (type != 'goon') {
        this.showDialog = false
      }
    },
  },
};
</script>

<style>
.avue-crud__pagination {
  margin-top: 0;
  padding: 0;
}
.el-input-group__append {
  padding: 0 8px;
}
</style>
